import BatchOperation from "@/components/BatchOperation";
import PermissionControl from "@/components/PermissionControl/index";
import { batchIntegralChangeApproval, getIntegralList, integralChangeApproval } from "@/services/patient/integralApi";
import { showMsg } from "@/utils/utils";
import { ModalForm, ProFormTextArea } from "@ant-design/pro-form";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { useRef, useState } from "react";

const ExamineTab = () => {

  const actionRef = useRef<ActionType>();
  const [open, setOpen] = useState<boolean>(false);
  const [type, setType] = useState<number>(1);
  const [batch, setBatch] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [editRowData, setEditRowData] = useState<PATIENT.IntegralInfo>();

  const columns: ProColumns<PATIENT.IntegralInfo>[] = [
    {
      title: '患者编号',
      dataIndex: 'patient_id',
      colSize: 2.5
    },
    {
      title: '姓名',
      dataIndex: 'patient_name',
      colSize: 2.5
    },
    {
      title: '身份证/住院号',
      dataIndex: 'identity_no',
      colSize: 3
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      colSize: 2.5
    },
    {
      title: '增减积分',
      dataIndex: 'integral',
      search: false
    },
    {
      title: '操作人',
      dataIndex: 'approve_user_name',
      search: false
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: '15%',
      render: (_, record, idx, action) => [
        <div key="batch" style={{ display: 'inline-flex', gap: 24 }}>
          <PermissionControl key="add" action_id="900901008">
            <a onClick={() => {
              setEditRowData(record); setType(1); setOpen(true);
              actionRef.current?.reload();
            }}>审批通过</a>
          </PermissionControl>
          <PermissionControl key="sub" action_id="900901009">
            <a onClick={() => {
              setEditRowData(record); setType(0); setOpen(true);
              actionRef.current?.reload();
            }}>审批拒绝</a>
          </PermissionControl>
        </div >
      ]
    }
  ];

  const cleanModalState = () => {
    setEditRowData(undefined);
    setBatch(false);
    setOpen(false);
  };

  const onFinish = async ({ approval_explain }: FormDataType) => {
    try {
      const approval_status = type === 1 ? 'N' : 'D';
      if (batch) {
        await batchIntegralChangeApproval({ approval_ids: selectedRows as string[], approval_status, approval_explain });
      } else {
        const { approval_id = '' } = editRowData || {};
        const actionId = type === 1 ? '900901013' : '900901014';
        await integralChangeApproval({ approval_id, approval_status, submit_explain: approval_explain }, actionId);
      }
      showMsg('提交成功', 'success');
      cleanModalState();
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    } finally {
      actionRef.current?.reload();
    }
  };

  return <>
    <ProTable
      actionRef={actionRef}
      rowKey="approval_id"
      className='mytable'
      cardProps={{ style: { paddingTop: 0 } }}
      options={false}
      bordered
      columns={columns}
      search={{
        span: 2,
        labelWidth: 'auto',
        collapsed: false,
        collapseRender: false,
        style: { padding: '0 6px 0 20px' },
        optionRender: (_, __, [, queryBtn]) => [queryBtn]
      }}
      request={async (params) => {
        try {
          const res = await getIntegralList({ ...params });
          return { success: true, data: res.record_list, total: res.sum_record_num };
        } catch (reason) {
          return { success: false, data: [] };
        }
      }}
      toolbar={{ style: { borderTop: '4px solid #eee', paddingTop: 8 } }}
      toolBarRender={() => [
        <div key="batch">
          <PermissionControl key="add" action_id="900901011">
            <BatchOperation
              onChange={() => actionRef.current?.clearSelected?.()}
              onOk={async option => {
                if (selectedRows?.length === 0) {
                  showMsg('请选择数据');
                  return;
                }
                setType(option.value); setBatch(true); setOpen(true);
              }}
              options={[
                { label: '审批通过', value: 1, confirm: false },
                { label: '审批拒绝', value: 0, confirm: false }
              ]} />
          </PermissionControl>
        </div>
      ]}
      rowSelection={{ onChange: setSelectedRows }}
      pagination={{ showQuickJumper: true }}
    />
    <ModalForm<FormDataType>
      width={400}
      layout="horizontal"
      visible={open}
      title={`${batch ? '批量' : ''}审批${operationType[type]}`}
      modalProps={{ maskClosable: false, destroyOnClose: true, onCancel: cleanModalState }}
      onFinish={onFinish}
    >
      <ProFormTextArea name="approval_explain" label={type === 1 ? '说明' : '拒绝原因'} required={false} />
    </ModalForm>
  </>;
};

export default ExamineTab;

type FormDataType = { approval_explain: string };

const operationType = ['拒绝', '通过'];
